package com.zss.leetcode;


/**
 * 链表反转
 * @author fuguozhang
 * @create 2022/5/18
 */
public class ReverseListNode {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(4);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(6);
        ListNode node5 = new ListNode(8);
        node1.setNext(node2);
        node2.setNext(node3);
        node3.setNext(node4);
        node4.setNext(node5);
        ListNode res = reverseListNode(node1);
        while (res != null){
            System.out.println(res.val);
            res = res.next;
        }
        System.out.println("============");
        res = reverseListNode(node5);
        while (res != null){
            System.out.println(res.val);
            res = res.next;
        }
    }

    /**
     * 迭代
     * @param head
     * @return
     */
    public static ListNode reverseListNode(ListNode head){
        ListNode curr = head;
        ListNode prev = null;
        while (curr != null){
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }

    /**
     * 递归
     * @param head
     * @return
     */
    public static ListNode reverseListNode2(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = reverseListNode2(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static class ListNode{
        private int val;
        private ListNode next;

        public ListNode(int val){
            this.val = val;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }
    }
}
